<?php
/* {
Citru - www.citru.se
See license.txt for copyright and license information.
} */

if(!defined("_CITRU")) {die('This file should not be accessed directly.');}
require_once 'DbModule.php';

class MysqlDbModule implements DbModule {
	
	private $dbConnection;
	private $dbName;
	
	function __construct($db_host, $db_user, $db_pass, $db_name) {
		$dbConnection = @mysql_connect($db_host, $db_user, $db_pass);
		if(!$dbConnection) {
			throw new Exception('Could not connect to database server, check host username and password.');
		}
		if(!mysql_select_db($db_name, $dbConnection)) {
			throw new Exception('Could not select database. Either the database does not exist or the user is not allowed to use it.');
		}
		mysql_query('SET NAMES utf8');
		mysql_query('SET CHARACTER SET utf8');
	}
	
	public function findFirst($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['condition'])) return false;
		if (!isset($params['columns'])) $params['columns'] = "*";
		if (!isset($params['order'])) $params['order'] = "id DESC";
				
		$params = $this->escapeArray($params);
		$condition = $this->generateCondition($params['condition']);
		
		$query = "SELECT ".$params['columns']." FROM `".$params['table']."` WHERE ".$condition." ORDER BY ".$params['order']." LIMIT 1";
		$result = mysql_query($query);
		
		$this->checkResult($result);	
		$row = mysql_fetch_assoc($result);
		return $row;
	}
	
	public function findAll($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['condition'])) return false;
		if (!isset($params['columns'])) $params['columns'] = "*";
		if (!isset($params['order'])) $params['order'] = "id DESC";
		if (!isset($params['limit'])) $params['limit'] = "";
		
		$params = $this->escapeArray($params);
		$condition = $this->generateCondition($params['condition']);
		if($params['limit'] != "") {
			$limit = " LIMIT ".$params['limit'];
		}
		
		$query = "SELECT ".$params['columns']." FROM `".$params['table']."` WHERE ".$condition." ORDER BY ".$params['order'].$limit;
		$result = mysql_query($query);
		
		$this->checkResult($result);
		$rows = array();
		while( $r = mysql_fetch_assoc($result) ) {
			$rows[] = $r;
		}
		return $rows;
	}
	
	public function insertRow($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['set'])) return false;
	
		$params = $this->escapeArray($params);
		foreach( $params['set'] as $key => $val) {
			$columns .= "`".$key."`, ";
			$values .= "'".$val."', ";
		}
		$columns = substr($columns, 0, -2);
		$values = substr($values, 0, -2);
		
		$query = "INSERT INTO `".$params['table']."` ( ".$columns." ) VALUES ( ".$values." );";
		$result = mysql_query($query);
		
		$this->checkResult($result);	
		return $result;
	}
	
	public function updateRow($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['condition'])) return false;
		if (!isset($params['set'])) return false;
		$params = $this->escapeArray($params);

		$set = $this->generateKeyValString($params['set']);
		$condition = $this->generateCondition($params['condition']);
		
		$query = "UPDATE `".$params['table']."` SET $set WHERE ".$condition." LIMIT 1 ;";
		$result = mysql_query($query);
		
		$this->checkResult($result);		
		return $result;
	}
	
	public function deleteRow($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['condition'])) return false;
		$params = $this->escapeArray($params);

		$condition = $this->generateCondition($params['condition']);
		
		$query = "DELETE FROM `".$params['table']."` WHERE ".$condition." LIMIT 1 ;";
		$result = mysql_query($query);
		
		$this->checkResult($result);		
		return $result;
	}
	
	public function addTable($params=array()) {
		if (!isset($params['table'])) return false;
		if (!isset($params['columns'])) return false;
		$params = $this->escapeArray($params);
		
		foreach($params['columns'] as $val) {
			$columns .= '`'.$val[0].'` '.$val[1].', ';
		}
		$columns = substr($columns, 0, strlen($columns)-2);
		
		if(isset($params['primary_key'])) {
			$primary_key = ', PRIMARY KEY (`'.$params['primary_key'].'`)';
		}
		
		$query = "CREATE TABLE IF NOT EXISTS `".$params['table']."` (".$columns.$primary_key.")";
		$result = mysql_query($query);
		
		$this->checkResult($result);		
		return $result;
	}
	
	
	private function checkResult($result) {
		if (!$result) {
		    $message  = 'Invalid query: ' . mysql_error() . "\n";
		    $message .= 'Whole query: ' . $query;
		    die($message);
		}
	}
	
	private function generateKeyValString($array=array(), $separator=", ") {
		$data = array(); 
		foreach($array as $key=>$val) {
			$data[] = "`$key`='$val'"; 
		}
		return implode($separator, $data);
	}
	
	private function generateCondition($conditionArray=array()) {
		$condition = "";
		foreach($conditionArray as $a) {
			$condition .= "`".$a[0]."` ".$a[1]." '".$a[2]."' ".$a[3]." ";
		}
		return $condition;
	}
	
	private function escapeArray($array=array()) {
		if(!is_array($array)) {
			return mysql_real_escape_string($array);
		}
		$return = array();
		foreach($array as $key=>$val) {
			if(get_magic_quotes_gpc()) {
				$key = stripslashes($key);
				if(!is_array($val)) {
					$val = stripslashes($val);
				}
			}
			if(is_array($val)) {
				$return[mysql_real_escape_string($key)] = $this->escapeArray($val);
			} else {
				$return[mysql_real_escape_string($key)] = mysql_real_escape_string($val);
			}
		}
		return $return;
	}
	
}

?>